import prompt from '../../utils/prompt.js';
import Api from '../../utils/api.js';
import {
  checkRequire,
  checkLater,
  checkEarlier
} from '../../utils/validator.js';

const app = getApp();

// components/propertyForm/propertyForm.js
Component({

  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    serviceTypeList: ['办公室打扫', '办公区打扫', '办公区维修', '宿舍维修', '宿舍卫生打扫'], // 服务类型列表

    location: '', // 地点
    time: '', // 时间
    serviceType: '', // 服务类型

    ps_location: true,
    ps_time: true,
    ps_serviceType: true
  },

  /**
   * 组件的方法列表
   */
  methods: {

    /* --======================数据接口======================-- */
    // 表单提交
    async submitProperty () {
      const param = {
        'commercialType': this.data.serviceType,
        'loc': this.data.location,
        'time': this.data.time
      };
      const res = await Api.applyService(param, app.globalData.sessionKey);
      if (res) {
        prompt.showToast('预约物业服务成功', 'success', { mask: true });
        setTimeout(() => {
          wx.navigateBack({
            delta: 1
          });
        }, 2000);
      }
    },

    /* --======================功能函数======================-- */
    // 检查输入
    checkInput () {
      let ps_serviceType = false;
      let ps_time = false;
      let ps_location = false;

      ps_serviceType = checkRequire(this.data.serviceType, '请选择或输入服务类型');
      this.setData({ ps_serviceType });

      if (ps_serviceType) {
        const current = new Date();
        const sevenDays = 7 * 24 * 60 * 60 * 1000;
        ps_time = (
          checkRequire(this.data.time, '请选择服务时间') &&
          checkEarlier(new Date(this.data.startDateTime), new Date(current.getTime() + sevenDays), '请选择7日以内的时间') &&
          checkLater(new Date(this.data.time), current, '无效的服务时间')
        );
        this.setData({ ps_time });
      }

      if (ps_time) {
        ps_location = checkRequire(this.data.location, '请输入服务地点');
        this.setData({ ps_location });
      }

      return (
        ps_serviceType &&
        ps_time &&
        ps_location
      );
    },

    /* --======================事件处理======================-- */
    // 数输入事件
    handleInput (e) {
      const param = {};
      param[e.currentTarget.dataset.state] = e.detail.value;
      this.setData(param);
    },
    // 获取 picker input 组件值
    handlePickerInputValue (e) {
      const param = {};
      param[e.currentTarget.dataset.value] = e.detail.value;
      this.setData(param);
    },
    // 表单提交
    handleSubmit () {
      if (this.checkInput()) {
        this.submitProperty();
      }
    }
  }
});
